package com.ganzalang.gmall.gmallfreemarker.intercepter;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ganzalang.gmall.gmallfreemarker.api.dto.UserDTO;
import com.ganzalang.gmall.gmallfreemarker.util.JwtUtil;
import com.google.common.collect.Sets;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    public static final String AUTHORIZSTION_HEADER_KEY = "Authorization";
    @Resource
    JwtUtil jwtUtil;

    /**
     * 不需要校验权限的路径
     */
    private static final Set<String> notNeedCheck = Sets.newHashSet(
            "/error"
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        StringBuffer requestURL = request.getRequestURL();
        String token = request.getHeader(AuthInterceptor.AUTHORIZSTION_HEADER_KEY);
        String authorization = request.getParameter("Authorization");

        if (StringUtils.isEmpty(token)) {
            token = authorization;
        }

        if (notNeedCheck.contains(requestURI)) {
            return true;
        }
        if (check(token)) {
            return true;
        }
        log.warn("AuthInterceptor intercept! Request uri is :{}", requestURI);
        return false;
    }

    private boolean check(String token) {
        if (!StringUtils.isEmpty(token)) {
            token = token.replace(JwtUtil.BEARER_KEY, "");
            DecodedJWT decodedJWT = jwtUtil.verifyJwt(token);
            String userDTOJsonStr = decodedJWT.getAudience().get(0);
            UserDTO userDTO = JSON.parseObject(userDTOJsonStr, UserDTO.class);
            log.info("decodedJWT:{}", JSON.toJSONString(decodedJWT));
            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
